<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="">
          <el-input v-model="searchInfo.UserName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <warning-bar title="注：右上角头像下拉可切换角色" />
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDrawer('新增', null)">新增用户</el-button>
      </div>
      <el-table :data="sortedData" @sort-change="sortChange" @selection-change="handleSelectionChange">
        <el-table-column align="left" label="用户ID" min-width="180" prop="ID" />
        <el-table-column align="left" label="用户名" min-width="150" prop="UserName" />
        <el-table-column align="left" label="用户DID" min-width="150" prop="Did" />
        <el-table-column align="left" label="账号" min-width="150" prop="NickName" />
        <el-table-column align="left" label="权限级别" min-width="180" prop="UserLevel" sortable="custom"/>
        <el-table-column align="left" label="用户状态" min-width="180" prop="UserStatus" sortable="custom">
          <template #default="scope">
            <span>{{ formatStatus(scope.row.UserStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="所属节点" min-width="180" prop="NodeId" />
        <el-table-column align="left" label="用户来源" min-width="180" prop="UserSource" />
        <el-table-column align="left" label="缴费情况" min-width="180" prop="UserSourceType" />
        <el-table-column label="操作" min-width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="eye" @click="openDrawer('编辑', scope.row)">查看详情</el-button>
            <el-button type="danger" link icon="delete" @click="deleteUserFunc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>


     <!-- 新增用户抽屉 -->
     <el-drawer v-model="drawerVisible" size="60%" :before-close="closeDrawer" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ drawerTitle }}</span>
          <div>
            <el-button @click="closeDrawerFun">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
        </div>
      </template>

      <el-form :model="userInfo" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="用户名" prop="UserName">
          <el-input v-model="userInfo.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userInfo.password" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="NickName">
          <el-input v-model="userInfo.nickName" />
        </el-form-item>
        <el-form-item label="手机号" prop="UserPhone">
          <el-input v-model="userInfo.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email" />
        </el-form-item>
<!--        <el-form-item label="权限角色" prop="authorityId">-->
<!--          <el-select v-model="userInfo.authorityId" placeholder="请选择角色">-->
<!--            <el-option v-for="item in authOptions" :key="item.authorityId" :label="item.authorityName" :value="item.authorityId" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
    </el-drawer>

    <el-drawer v-model="visible" size="60%" :before-close="closeUserDetailDialog" :show-close="false">
      <template #header>
        <span class="text-lg">用户详情</span>
      </template>
      <el-form :model="userDetail" label-width="100px">
        <!-- 详情展示，修改为可编辑 -->
        <el-form-item label="用户名" prop="UserName">
          <el-input v-model="userDetail.UserName" disabled/>
        </el-form-item>
        <el-form-item label="用户DID">
          <el-input v-model="userDetail.DId" disabled />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="userDetail.NickName" disabled/>
        </el-form-item>
        <el-form-item label="权限级别">
          <el-input v-model="userDetail.UserLevel" disabled/>
        </el-form-item>
        <el-form-item label="用户状态">

          <el-select v-model="userDetail.UserStatus" placeholder="请选择用户状态">
            <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="所属节点">
          <el-input v-model="userDetail.NodeId" disabled/>
        </el-form-item>
        <el-form-item label="用户来源">
          <el-input v-model="userDetail.UserSource" disabled/>
        </el-form-item>
        <el-form-item label="缴费情况">
          <el-input v-model="userDetail.UserSourceType" disabled/>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="updateUser">保存</el-button>
          <el-button @click="closeUserDetailDialog">关闭</el-button>
        </span>
      </template>
    </el-drawer>

  </div>
</template>

<script setup>

import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getlistUser } from '@/api/userControl'
import { addNWYLUser } from '@/api/userControl'
import { deleteNWYLUser ,updateNWYLUser} from '@/api/userControl'




const searchInfo = reactive({ UserName: '' })

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const filteredData = ref([])
const drawerTitle = ref('')
const drawerVisible = ref(false)
const visible = ref(false)
const userInfo = ref({
  UserName: '',
  password: '',
  NickName: '',
  UserPhone: '',
  Email: '',
  authorityId: '',
  authorityIds: [],
  enable: 1,
})
const userDetail = ref({})
const rules = ref({
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
  nickName: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入合法手机号', trigger: 'blur' }],
  email: [{ pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱', trigger: 'blur' }],
  authorityId: [{ required: true, message: '请选择用户角色', trigger: 'blur' }],
})
const addUserDialog = ref(false)
const userDetailDialog = ref(false)
const authOptions = ref([])
const originalTableData = ref([]); // 用于保存原始数据



const statusOptions = ref([
  { label: '启用', value: 1 },
  {label: '停止', value: 2}
])

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async () => {
  try {
    const response = await getlistUser(page.value, pageSize.value);
    tableData.value = response.data.userList || []; // 确保是数组
    originalTableData.value = tableData.value;
    total.value = response.data.TotalNum; // 确保返回总数
    filteredData.value = [...tableData.value]; // 重置为有效数据
    console.log('response:', response.data);
    console.log('table:', tableData.value);
  } catch (error) {
    console.error('API Error:', error);
    ElMessage.error('获取数据失败');
  }
};


const openAddUserDialog = () => {
  addUserDialog.value = true
}

const closeAddUserDialog = () => {
  addUserDialog.value = false
}

const submitUserForm = () => {
  // 提交用户信息逻辑
  ElMessage.success('用户新增成功')
  closeAddUserDialog()
}

 const viewUserDetails = (row) => {
  userDetail.value = { ...row }; // 确保是一个新的对象
  visible.value = true;
};

const closeUserDetailDialog = () => {
  userDetailDialog.value = false
  visible.value=false
}

const sortInfo = reactive({
  prop: '',
  order: ''
})

const sortedData = computed(() => {
  filteredData.value=tableData.value
  let data = [...filteredData.value]
  if (sortInfo.prop && sortInfo.order) {
    data.sort((a, b) => {
      let aValue = a[sortInfo.prop]
      let bValue = b[sortInfo.prop]
      if (sortInfo.prop === 'status') {
        // 按照状态值排序
        aValue = statusOptions.value.find(option => option.value === a[sortInfo.prop]).label
        bValue = statusOptions.value.find(option => option.value === b[sortInfo.prop]).label
      }
      if (sortInfo.order === 'ascending') {
        return aValue > bValue ? 1 : -1
      } else {
        return aValue < bValue ? 1 : -1
      }
    })
  }
  console.log(data)
  return data
})

const onSubmit = () => {
  filteredData.value = originalTableData.value.filter(item =>
    item.UserName.includes(searchInfo.UserName)
  ) || []; // Fallback to an empty array if nothing matches
  tableData.value = [...filteredData.value];
}

const onReset = () => {
  searchInfo.UserName = '';
  tableData.value = [...originalTableData.value]; // originalTableData 需要保存原始数据
  filteredData.value = [...tableData.value];
}

const openDrawer = (title, row) => {
  drawerTitle.value = title === '新增' ? '新增用户' : '查看详情'
  if (row) {
    userDetail.value = row
    /* userInfo.DID = row.DID
    userInfo.userName = row.userName
    userInfo.idCard = row.idCard
    userInfo.phone = row.phone
    userInfo.bankCard = row.bankCard
    userInfo.auditProgress = row.auditProgress
    userInfo.auditStatus = row.auditStatus */
    visible.value = true
  } else {
    userInfo.DID = ''
    userInfo.userName = ''
    userInfo.idCard = ''
    userInfo.phone = ''
    userInfo.bankCard = ''
    userInfo.auditProgress = ''
    userInfo.auditStatus = ''
    drawerVisible.value = true
  }
  //drawerVisible.value = true
}

const closeDrawerFun=async()=>{
  drawerVisible.value = false
}

const deleteUserFunc = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗?', '删除确认', {
      type: 'warning'
    })
    console.log('删除的ID',row.ID)
    await deleteNWYLUser({"Id":row.ID})
    
    ElMessage.success('用户删除成功')
    getTableData()
  } catch (error) {
    // 取消删除操作或失败
  }
}

const submitForm = async () => {
  try {
    // 调用 API 添加服务
    console.log(userInfo.value)
    userInfo.value.authorityId=111
    userInfo.value.authorityIds[0]=userInfo.value.authorityId
    const req={
      ...userInfo.value
    }
    /* const res=await register(req) */
  /*   if(res.code===0){
      ElMessage({type:'success',message:'创建成功'})
    }
 */
    await addNWYLUser(userInfo.value)

    ElMessage.success('用户新增成功')
    /* closeDetailDialog() */
    drawerVisible.value = false
    await getTableData() // 刷新表格数据
  } catch (error) {
    console.error('新增用户失败', error)
    ElMessage.error('新增用户失败')
  }
  /* nextTick(() => {
    ElMessage.success('保存成功')
    closeDetailDialog()
  }) */
}

const sortChange = ({prop, order}) => {
  sortInfo.prop = prop
  sortInfo.order = order
  console.log('排序变化', prop, order)
}

const handleSelectionChange = (val) => {
  apis.value = val
  console.log('选择变化', val)
  // 选择变化逻辑
}

const formatStatus = (status) => {
  const statusOption = statusOptions.value.find(option => option.value === status)
  return statusOption ? statusOption.label : ''
}

const updateUser = async () => {
  try {
    console.log("用户信息：",userDetail.value.ID)
    console.log("用户信息：",userDetail.value.UserStatus)
    await updateNWYLUser({"UserId":userDetail.value.ID,"Status":Number(userDetail.value.UserStatus)}); // 调用更新用户的 API
    ElMessage.success('用户信息更新成功');
    closeUserDetailDialog();
    getTableData(); // 刷新表格数据
  } catch (error) {
    console.error('更新用户信息失败', error);
    ElMessage.error('更新用户信息失败');
  }
};



watch(() => tableData.value, () => {
  // watch代码
})

getTableData()
</script>

<style scoped>
/* Add your styles here */
</style>